package com.yuehuanghun.admin.core.controller.system;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yuehuanghun.admin.core.config.Constants;
import com.yuehuanghun.admin.core.config.UserConstants;
import com.yuehuanghun.admin.core.config.util.UserUtils;
import com.yuehuanghun.admin.core.domain.SysMenu;
import com.yuehuanghun.admin.core.domain.vo.TreeSelect;
import com.yuehuanghun.admin.core.service.ISysMenuService;
import com.yuehuanghun.framework.annotation.Log;
import com.yuehuanghun.framework.annotation.Log.BusinessType;
import com.yuehuanghun.framework.exception.ValidateException;
import com.yuehuanghun.framework.util.Kv;
import com.yuehuanghun.framework.util.StringUtils;
import com.yuehuanghun.framework.web.BaseResource;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;

/**
 * 菜单信息
 * 
 * @author yadmin
 */
@RestController
@RequestMapping("/system/menu")
@SaCheckLogin
public class SysMenuController extends BaseResource {
	@Autowired
	private ISysMenuService menuService;

	/**
	 * 获取菜单列表
	 */
	@GetMapping("/list")
	@SaCheckPermission("system:menu:list")
	public List<SysMenu> list(SysMenu menu) { //NOSONAR
		Long userId = UserUtils.getCurrentUser().getUserId();
		return menuService.getMenuList(menu, userId);
	}

	/**
	 * 根据菜单编号获取详细信息
	 */
	@GetMapping(value = "/{menuId}")
	@SaCheckPermission("system:menu:query")
	public SysMenu getInfo(@PathVariable Long menuId) {
		return menuService.selectMenuById(menuId);
	}

	/**
	 * 获取菜单下拉树列表
	 */
	@GetMapping("/treeselect")
	public List<TreeSelect> treeselect(SysMenu menu) { //NOSONAR
		Long userId = UserUtils.getCurrentUser().getUserId();
		List<SysMenu> menus = menuService.getMenuList(menu, userId);
		return menuService.buildMenuTreeSelect(menus);
	}

	/**
	 * 加载对应角色菜单列表树
	 */
	@SuppressWarnings("rawtypes")
	@GetMapping(value = "/roleMenuTreeselect/{roleId}")
	public Map roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
		List<SysMenu> menus = menuService.getMenuList(UserUtils.getCurrentUser().getUserId());
		return Kv.by("checkedKeys", menuService.selectMenuListByRoleId(roleId).stream().map(item -> item.toString()).collect(Collectors.toList()))
				.set("menus", menuService.buildMenuTreeSelect(menus));
	}

	/**
	 * 新增菜单
	 */
	@Log(title = "菜单管理", businessType = BusinessType.INSERT)
	@PostMapping
	@SaCheckPermission("system:menu:add")
	public void add(@Validated @RequestBody SysMenu menu) { //NOSONAR
		if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
			throw new ValidateException("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
		} else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
				&& !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) { //NOSONAR
			throw new ValidateException("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
		}
		menuService.add(menu);
	}

	/**
	 * 修改菜单
	 */
	@Log(title = "菜单管理", businessType = BusinessType.UPDATE)
	@PutMapping
	@SaCheckPermission("system:menu:edit")
	public void edit(@Validated @RequestBody SysMenu menu) { //NOSONAR
		if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
			throw new ValidateException("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在"); //NOSONAR
		} else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
				&& !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) { //NOSONAR
			throw new ValidateException("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
		} else if (menu.getMenuId().equals(menu.getParentId())) {
			throw new ValidateException("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
		}
		menuService.updateById(menu);
	}

	/**
	 * 删除菜单
	 */
	@Log(title = "菜单管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{menuId}")
	@SaCheckPermission("system:menu:remove")
	public void remove(@PathVariable("menuId") Long menuId) {
		if (menuService.hasChildByMenuId(menuId)) {
			throw new ValidateException("存在子菜单,不允许删除");
		}
		if (menuService.checkMenuExistRole(menuId)) {
			throw new ValidateException("菜单已分配,不允许删除");
		}
		menuService.deleteById(menuId);
	}
}